from django.conf import settings
from django.contrib import admin
from .models import BlogCounts, NavUrlSetting, SiteSetting
from import_export.admin import ImportExportModelAdmin
from import_export import resources
from django.http import HttpResponseRedirect
from django.shortcuts import reverse

# from

# 博客后台站点名称
admin.site.site_header = settings.BLOG_NAME + '博客后台管理系统'
admin.site.site_title = settings.BLOG_NAME + '管理系统'


@admin.register(SiteSetting)
class SiteSettingAdmin(admin.ModelAdmin):
    list_display = ['title', 'keywords', 'description', 'push_url']

    def has_add_permission(self, request):
        count = self.model.objects.all().count()
        if count >= 1:
            return False
        else:
            return super().has_add_permission(request)

    def has_delete_permission(self, request, obj=None):
        return False

    def changelist_view(self, request, extra_context=None):
        site_setting = self.model.objects.all()
        count = site_setting.count()
        if count == 1:
            return HttpResponseRedirect('/admin/bbd_admin/sitesetting/%s/change/' % site_setting.first().id)
        else:
            return super().changelist_view(request, extra_context=None)


class BlogCountsResource(resources.ModelResource):
    class Meta:
        model = BlogCounts


class NavUrlSettingResource(resources.ModelResource):
    class Meta:
        model = NavUrlSetting


@admin.register(BlogCounts)
class BlogCountsAdmin(ImportExportModelAdmin):
    resource_class = BlogCountsResource
    list_display = ['create_date', 'url', 'counts']


@admin.register(NavUrlSetting)
class NavUrlSettingAdmin(ImportExportModelAdmin):
    resource_class = NavUrlSettingResource
    list_display = ['name', 'link', 'index']
    list_editable = ['index']
